import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { UrlConfigComponent } from '../url-config/url-config.component';
import {CookieService} from 'ngx-cookie-service';

@Component({
  selector: 'app-component',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  constructor(
    public login: FormBuilder,
    private message: NzMessageService,
    private router: Router,
    private httpClient: HttpClient,
    private config: UrlConfigComponent,
    private cookieService: CookieService,
  ) {
  }

  JSON = JSON;
  public validateForm!: FormGroup;
  public passwordVisible = false;

  // 提交表单
  onSubmit(): void {

    // 更新表单未通过验证的控件高亮显示
    // tslint:disable-next-line:for in forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    // 如果验证通过
    if (this.validateForm.status === 'INVALID') {
      this.message.create('warning', '请填写用户名和密码');
      return;
    }

    const cookieValue = this.cookieService.get('ku-site');
    // tslint:disable-next-line:no-console
    console.info('cookieValue:' + cookieValue);

    // 如果验证通过
    if (this.validateForm.status === 'VALID') {
      const {username, password} = this.validateForm.value;
      if (username === 'admin' && password === '123456') {
        this.message.create('success', '登录成功!');
        this.router.navigate(['/home']).then(r => console.log('login success!'));
      } else {
        this.message.create('error', '用户名密码错误!');
        this.httpClient.get(this.config.getTestUrl()).subscribe((response: any) => {
          console.log(response);
        });
      }
    }
  }

  // 初始化
  ngOnInit(): void {
    this.validateForm = this.login.group({
      username: ['', [Validators.required]],
      password: ['', [Validators.required]],
      remember: [true]
    });
  }

}
